from django.shortcuts import render
from django.http import HttpResponse
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidAppIdException
from wechatpy import parse_message
from wechatpy.replies import TextReply
from wechatpy.replies import create_reply



# Create your views here.


def test(request):
    return HttpResponse('hello world')


def index(request):
    if request.method == 'GET':
        signature = request.GET.get('signature')
        timestamp = request.GET.get('timestamp')
        nonce = request.GET.get('nonce')
        echostr = request.GET.get('echostr')
        token = "szy4760699"
        try:
            check_signature(token, signature, timestamp, nonce)
            return HttpResponse(echostr)
        except InvalidAppIdException:
            pass
    else:
        msg = parse_message(request.body)
        if msg.type == 'text':
            reply = create_reply('Shidan', message=msg)
        else:
            reply = create_reply('暂时只支持文字', message=msg)
        response = HttpResponse(reply.render(), content_type='application/xml')
        return response
